package com.vca.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.vca.common.constants.SmsConstants;
import com.vca.common.vo.SendSmsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 发送短信工具——阿里云
 *
 * @author chenbing
 * @date 2022/4/26   8:07
 */
public class SendSmsUtils {


    private static final Logger logger = LoggerFactory.getLogger(SendSmsUtils.class);

    public static void main() throws Exception {
        HashMap<String, Object> justPram = new HashMap<>();
        justPram.put("name", "活动名称");
        justPram.put("start_time", "2022年12月09日");
        System.out.println("JSONObject.toJSONString(justPram) = " + JSONObject.toJSONString(justPram));
        SendSmsVo sendSmsVo = new SendSmsVo();
        sendSmsVo.setAccessKeyIdSms("ULZah0Yxq41iLeaf");
        sendSmsVo.setAccessKeySecretSms("EoTHSzyYaArFn62wEinR1VSfb6wWTQ");
        sendSmsVo.setTemplateParam(JSONObject.toJSONString(justPram));
        sendSmsVo.setSignName(SmsConstants.SEND_SMS_OF_SIGN_NAME);
        sendSmsVo.setTempLateCode(SmsConstants.SEND_SMS_OF_VERIFICATION_CODE);
        sendSmsVo.setPhoneNumber("15364268364");
        SendSmsUtils.sendSms(sendSmsVo);
    }

    /**
     * 使用AK&SK初始化账号Client
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 短信发送访问域名 Send SMS to access domain name  "dysmsapi.aliyuncs.com"
        config.endpoint = SmsConstants.SEND_SMS_TO_ACCESS_DOMAIN_NAME;
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    /**
     *@Description:发送短信
     *@author:chenbing
     *@date 2023/1/4 10:13
     */
    public static Boolean sendSms(SendSmsVo sendSmsVo) throws Exception {
        System.getProperties().clear();
        com.aliyun.dysmsapi20170525.Client client = SendSmsUtils.createClient(sendSmsVo.getAccessKeyIdSms(), sendSmsVo.getAccessKeySecretSms());
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(sendSmsVo.getPhoneNumber())
                .setSignName(sendSmsVo.getSignName())
                .setTemplateCode(sendSmsVo.getTempLateCode())
                .setTemplateParam(sendSmsVo.getTemplateParam());
        logger.info("开始发送短信......");
        // 复制代码运行请自行打印 API 的返回值
        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
        String code = sendSmsResponse.getBody().getCode();
        logger.info("code--->{}", code);
        Map<String, String> headers = sendSmsResponse.getHeaders();
        logger.info("==========发送短信headers=========\n" + headers);
        if (!com.aliyun.teautil.Common.equalString(code, "OK")) {
            logger.info("发送失败......");
            logger.info("错误信息: {}", sendSmsResponse.body.message + "");
            return false;
        }
        logger.info("发送成功......");
        return true;
    }

    public void mainProxy() {
        HashMap<String, Object> justPram = new HashMap<>();
        justPram.put("name", "活动名称");
        justPram.put("start_time", "2022年12月09日");
        System.out.println("JSONObject.toJSONString(justPram) = " + JSONObject.toJSONString(justPram));
        SendSmsVo sendSmsVo = new SendSmsVo();
        sendSmsVo.setAccessKeyIdSms("ULZah0Yxq41iLeaf");
        sendSmsVo.setAccessKeySecretSms("EoTHSzyYaArFn62wEinR1VSfb6wWTQ");
        sendSmsVo.setTemplateParam(JSONObject.toJSONString(justPram));
        sendSmsVo.setSignName(SmsConstants.SEND_SMS_OF_SIGN_NAME);
        sendSmsVo.setTempLateCode(SmsConstants.SEND_SMS_OF_VERIFICATION_CODE);
        sendSmsVo.setPhoneNumber("15364268364");
        SendSmsUtils.sendSmsProxy(sendSmsVo);
    }

    /**
     * @Description:发送短信[Proxy]
     * @author:chenbing
     * @date 2023/1/4 10:13
     */
    public static Boolean sendSmsProxy(SendSmsVo sendSmsVo) {
        try {
            String sendUrl  = getSendRequestUrl(sendSmsVo.getPhoneNumber(), sendSmsVo.getTempLateCode(), sendSmsVo.getTemplateParam(), sendSmsVo.getAccessKeyIdSms(), sendSmsVo.getAccessKeySecretSms(), sendSmsVo.getSignName());
            System.out.println("sendUrl = " + sendUrl);
            String xml = HttpClientUtils.doGetRequest(sendUrl);
            HashMap<String, Object> map = XmlUtil.xmlToMap(xml);
            logger.info("xml--->{}",JSONObject.toJSONString(map));
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(map));
            if (!com.aliyun.teautil.Common.equalString(String.valueOf(jsonObject.get("Code")), "OK")) {
                logger.info("发送失败......");
                logger.info("错误信息: {}", jsonObject);
                return Boolean.FALSE;
            }
            logger.info("发送成功......");
            return Boolean.TRUE;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *@Description:获取短信发送Url
     *@author:chenbing
     *@date 2023/1/10 13:10
     */
    private static String getSendRequestUrl(String telephone, String templateCode, String templateParam, String accessKeyIdSms, String accessKeySecretSms, String signName)
            throws Exception {
        java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        df.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));// 这里一定要设置GMT时区
        java.util.Map<String, String> paras = new HashMap<String, String>();
        // 1. 系统参数
        paras.put("SignatureMethod", "HMAC-SHA1");
        paras.put("SignatureNonce", java.util.UUID.randomUUID().toString());
        paras.put("AccessKeyId", accessKeyIdSms);
        paras.put("SignatureVersion", "1.0");
        paras.put("Timestamp", df.format(new java.util.Date()));
        paras.put("Format", "XML");
        // 2. 业务API参数
        paras.put("Action", "SendSms");
        paras.put("Version", "2017-05-25");
        paras.put("RegionId", "cn-hangzhou");
        paras.put("PhoneNumbers", telephone);
        paras.put("SignName", signName);
        paras.put("TemplateParam", templateParam);
        paras.put("TemplateCode", templateCode);
        // 3. 去除签名关键字Key
        if (paras.containsKey("Signature")) {
            paras.remove("Signature");
        }
        // 4. 参数KEY排序
        java.util.TreeMap<String, String> sortParas = new java.util.TreeMap<String, String>();
        sortParas.putAll(paras);
        // 5. 构造待签名的字符串
        java.util.Iterator<String> it = sortParas.keySet().iterator();
        StringBuilder sortQueryStringTmp = new StringBuilder();
        while (it.hasNext()) {
            String key = it.next();
            sortQueryStringTmp.append("&").append(specialUrlEncode(key))
                    .append("=").append(specialUrlEncode(paras.get(key)));
        }
        String sortedQueryString = sortQueryStringTmp.substring(1);// 去除第一个多余的&符号
        StringBuilder stringToSign = new StringBuilder();
        stringToSign.append("GET").append("&");
        stringToSign.append(specialUrlEncode("/")).append("&");
        stringToSign.append(specialUrlEncode(sortedQueryString));
        String sign = sign(accessKeySecretSms + "&", stringToSign.toString());
        // 6. 签名最后也要做特殊URL编码
        String signature = specialUrlEncode(sign);
        // 最终打印出合法GET请求的URL
        return "http://dysmsapi.aliyuncs.com/?Signature=" + signature + sortQueryStringTmp;
    }

    private static String specialUrlEncode(String value) throws Exception {
        return java.net.URLEncoder.encode(value, "UTF-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
    }

    private static String sign(String accessSecret, String stringToSign) throws Exception {
        javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1");
        mac.init(new javax.crypto.spec.SecretKeySpec(accessSecret.getBytes("UTF-8"), "HmacSHA1"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        return new sun.misc.BASE64Encoder().encode(signData);
    }
}
